from django.contrib import admin
from django.http import HttpResponse
import xlwt
from django.utils.http import quote  # 添加这个导入
from django.db.models import Q

from datetime import datetime
from django.contrib.admin import SimpleListFilter
from django.core.paginator import Paginator
from django.urls import path
from django.http import JsonResponse
from django.shortcuts import render
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User
from django.utils.html import format_html
from django.urls import reverse
from .models import (

    SkuKeywords, 
    FollowPrice
   
)
import xlrd
import io
from django.conf import settings
from django.templatetags.static import static

class FollowPriceStatusFilter(SimpleListFilter):
    title = '跟价状态'
    parameter_name = 'follow_status'

    def lookups(self, request, model_admin):
        return (
            ('followed', '已跟价'),
            ('unfollowed', '未跟价'),
        )

    def queryset(self, request, queryset):
        # 已跟价：itemid 非空且长度>=5
        if self.value() == 'followed':
            return queryset.filter(itemid__isnull=False).exclude(itemid='').extra(where=["LENGTH(itemid) >= 5"])
        # 未跟价：itemid 为空或者长度<5
        if self.value() == 'unfollowed':
            return queryset.extra(where=["itemid IS NULL OR itemid = '' OR LENGTH(itemid) < 5"])
        return queryset

# Register your models here.
admin.site.site_title = '竞品管理系统'
admin.site.index_title = '竞品管理索引'
#网页列标题
admin.site.site_header='竞品管理'
#网页标题
admin.site.site_title='竞品管理-信息管理'
#首页标语
admin.site.index_title = '竞品管理-系统管理'
 
 


# class ShopWhiteListAdmin(admin.ModelAdmin):
#     list_display = ['shop_type', 'shop_name']  # 在列表页面显示的字段
#     search_fields = ('shop_type', 'shop_name')
#     list_per_page = 20

#     def get_paginator(self, request, queryset, per_page):
#         return Paginator(queryset, 20)

# admin.site.register(ShopWhiteList, ShopWhiteListAdmin)
# 注册模型表
# admin.site.register(DictType)


# class DictTypeAdmin(admin.ModelAdmin):
#     list_display = ['type_code', 'type_name']  # 在列表页面显示的字段
#     def get_paginator(self, request, queryset, per_page):
#         return Paginator(queryset, 20)
# 注册模型表
# admin.site.register(DictType, DictTypeAdmin)

# @admin.register(SkuKeywords)

class SkuKeyAdmin(admin.ModelAdmin):
    list_display = [
        'keywords',  'ebay', 'ali','amz','username', 'opdate','download_date',
        'get_row_actions'
    ]
    list_display_links = ('keywords','username')
    search_fields = ( 'keywords', 'username')
    list_filter = ['keywords', 'username', 'ebay', 'ali', 'amz']
    list_per_page = 20
    save_as = True
    actions = ['export_current_page']
    actions_on_top = True
    sort_by = ['keywords']
    
    def get_row_actions(self, obj):
        """获取行操作按钮"""
        if not obj:
            return ''
            
        # 获取各种URL
        change_url = f'/admin/app/skukeywords/{obj.id}/change/'
        delete_url = f'/admin/app/skukeywords/{obj.id}/delete/'
        history_url =  f'/admin/skukeywords/skukeywords_history/?keywords={obj.keywords}'
        history_url = f'/admin/app/skukeywords_history/?keywords={obj.keywords}'


        # follow_price_url = f'/admin/app/skukeywordsprice/?keywords_id={obj.keywords}'   
        follow_price_url = f'/admin/skukeywords/skukeywordsanotherproxy/?keywords={obj.keywords}'
        follow_price_url = f'/jobs/followprice/query1/?keywords={obj.keywords}'
        follow_price_url = f'/admin/skukeywords/skukeywordsanotherproxy/?keywords={obj.keywords}'
        follow_price_url = f'/admin/app/followprice/?q={obj.keywords}'




        # 使用format_html确保HTML安全性
        return format_html(
            '<a class="button" href="{}">编辑</a>&nbsp;'
            '<a class="button" href="{}">删除</a>&nbsp;'
            '<a class="button" href="{}">关键词下载历史</a>&nbsp;'
            '<a class="button" href="{}">去看下载产品并处理</a>',
            change_url,
            delete_url,
            history_url,
            follow_price_url
        )
    
    get_row_actions.short_description = '操作'
    get_row_actions.allow_tags = True

    def has_change_permission(self, request, obj=None):
        return True

    def has_delete_permission(self, request, obj=None):
        return True

    def has_view_permission(self, request, obj=None):
        return True

    def has_add_permission(self, request):
        return True

    def export_current_page(self, request, queryset):
        """导出当前页数据"""
        response = HttpResponse(content_type='application/ms-excel')
        response['Content-Disposition'] = f'attachment; filename="skukeywords_currentpage_{datetime.now().strftime("%Y%m%d_%H%M%S")}.xls"'
        
        wb = xlwt.Workbook(encoding='utf-8')
        ws = wb.add_sheet('SkuKeywords')
        
        # 自动生成列名
        row_num = 0
        fields = [field for field in self.model._meta.fields if field.name in self.list_display[:-1]]  # 排除 get_row_actions
        columns = [field.verbose_name or field.name for field in fields]
        
        # 设置列宽
        for i in range(len(columns)):
            ws.col(i).width = 256 * 20  # 20个字符宽度
        
        # 设置标题样式
        header_style = xlwt.XFStyle()
        header_style.font.bold = True
        
        for col_num, column_title in enumerate(columns):
            ws.write(row_num, col_num, column_title, header_style)
        
        # Write data rows
        for row in queryset:
            row_num += 1
            for col_num, field in enumerate(fields):
                value = getattr(row, field.name)
                ws.write(row_num, col_num, value)
        
        wb.save(response)
        return response
    
    export_current_page.short_description = "导出当前页数据"

    def get_fields(self, request, obj=None):
        """获取表单字段"""
        fields = super().get_fields(request, obj)
        if 'username' not in fields:
            fields = ['username'] + list(fields)
        return fields

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if hasattr(request.user, 'userprofile') and not request.user.userprofile.is_leader:
            return qs.filter(username=request.user.username)
        return qs

    def save_model(self, request, obj, form, change):
        if not change:  # 只在新增时设置 username
            obj.username = request.user.username
        obj.save()

    def get_readonly_fields(self, request, obj=None):
        """动态设置只读字段"""
        if obj:  # 编辑时
            return self.readonly_fields + ('username',)
        return self.readonly_fields

    def formfield_for_dbfield(self, db_field, request, **kwargs):
        """设置表单字段的初始值"""
        field = super().formfield_for_dbfield(db_field, request, **kwargs)
        if db_field.name == 'username':
            field.initial = request.user.username

        return field

    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        form.base_fields['keywords'].required = True  # 设置为必填
        form.base_fields['keywords'].label = format_html(
            '{}<span style="color: red;">*</span>', 
            'Keywords'
        )  # 添加红色星号
        return form

admin.site.register(SkuKeywords, SkuKeyAdmin) 




# class FollowPriceAdmin(admin.ModelAdmin):
#     list_display = [
#         'storename', 'shop_type', 'username', 'keywords','title', 'link', 'price',
#         'salesvolume', 'pic', 'price2', 'salesvolume2', 'pic2', 'itemid',
#         'lowvalue', 'username', 'opdate'
#     ]  # 在列表页面显示的字段
#     search_fields = ('shop_type', 'username', 'keywords', 'title', 'itemid')

#     def get_paginator(self, request, queryset, per_page):
#         return Paginator(queryset, 20)

# admin.site.register(FollowPrice, FollowPriceAdmin)


class FollowPriceHistoryAdmin(admin.ModelAdmin):
    list_display = [
        'id','storename', 'shop_type', 'keywords', 'pic', 'username', 'title', 'link',
        'price', 'salesvolume', 'price2', 'salesvolume2', 'pic2',
        'itemid', 'lowvalue', 'username', 'opdate'
    ]  # 在列表页面显示的字段
    search_fields = ('id','shop_type', 'username', 'keywords', 'title', 'itemid')
    def get_paginator(self, request, queryset, per_page):
        return Paginator(queryset, 20)
    def has_add_permission(self, request):
        return False
    
    # 禁用修改功能
    def has_change_permission(self, request, obj=None):
        return False
    
    # 禁用删除功能
    def has_delete_permission(self, request, obj=None):
        return False
    def get_queryset(self, request):
        """
        根据用户权限过滤数据
        """
        qs = super().get_queryset(request)
        # 检查用户是否为领导
        if hasattr(request.user, 'userprofile') and not request.user.userprofile.is_leader:
            # 不是领导，只显示自己的数据
            return qs.filter(username=request.user.username)
        # 是领导，显示所有数据
        return qs
    # 移除动作栏
    actions = None
     


# admin.site.register(FollowPrice, FollowPriceHistoryAdmin)
# admin.site.register(FollowPriceHistory, FollowPriceHistoryAdmin)




class CombinedAdminView(admin.ModelAdmin):
    def has_view_permission(self, request, obj=None):
        return request.user.has_perm("app.can_manage_followprice_admin")
    def has_change_permission(self, request, obj=None):
        return request.user.has_perm("app.can_manage_followprice_admin")
    def has_add_permission(self, request):
        return False
    def has_delete_permission(self, request, obj=None): 
        return False

    def changelist_view(self, request, extra_context=None):
        """
        重写默认的列表视图展示逻辑，用于同时获取并返回FollowPrice和SkuKeywords的数据列表。
        """
        FollowPrice_queryset = self.get_FollowPrice_data(request)
        SkuKeywords_queryset = self.get_SkuKeywords_data(request)
        is_leader = hasattr(request.user, 'userprofile') and request.user.userprofile.is_leader
        if not is_leader:
            # 非领导只能看到自己的数据
            FollowPrice_queryset = FollowPrice_queryset.filter(username=request.user.username)
            SkuKeywords_queryset = SkuKeywords_queryset.filter(username=request.user.username)
        # 以下是添加筛选条件的示例，你可以根据实际需求修改
        # queryset = queryset.filter(name__contains='example')
        paginator = Paginator(FollowPrice_queryset, 20)  # 每页20条
        page = 1  # 固定显示第一页
        FollowPrice_data=None
        SkuKeywords_data=None

        try:
            current_page = paginator.page(page)
            FollowPrice_data = list(current_page.object_list)  # 只获取第一页数据

        except:
            current_page = paginator.page(1)

        paginator0 = Paginator(SkuKeywords_queryset, 20)  # 每页20条
        page = 1  # 固定显示第一页
        
        try:
            current_page0 = paginator0.page(page)
            SkuKeywords_data = list(current_page0.object_list)  # 只获取第一页数据

        except:
            current_page0 = paginator0.page(1)
            SkuKeywords_data = list(current_page0.object_list)  # 只获取第一页数据

            
        context = {
            'FollowPrice': FollowPrice_data,
            'SkuKeywords': SkuKeywords_data,
            'module': 'query1',

            'pagination': {
                'current_page': page,
                'total_pages': paginator.num_pages,
                'total_items': paginator.count,
                'page_size': 20,
                'has_next': current_page.has_next(),
                'has_previous': current_page.has_previous()
            }
        }
        # context = {
        #     'FollowPrice': FollowPrice_data,
        #     'SkuKeywords': SkuKeywords_data,
        # }
        # 是返回处理结果的，要调用网页显示啊
        return render(request, 'FollowPrice2.html', context)

        # return JsonResponse(combined_data)

    def get_list_display(self, request):
        """
        根据请求的模型名称，决定返回哪些字段用于列表页面显示。
        如果是FollowPrice模型，则返回预先定义的字段列表；否则返回空列表。
        """
        model_name = request.GET.get('model', '')
        if model_name == 'FollowPrice':
            return [
                'storename', 'shop_type', 'username', 'keywords', 'title',
                'link', 'price', 'salesvolume', 'pic', 'price2',
                'salesvolume2', 'pic2', 'itemid', 'lowvalue', 'username',
                'opdate'
            ]
        return []

    def get_search_fields(self, request):
        """
        类似地，根据请求的模型名称，决定返回哪些字段用于搜索功能。
        如果是FollowPrice模型，则返回预先定义的搜索字段；否则返回空列表。
        """
        model_name = request.GET.get('model', '')
        if model_name == 'FollowPrice':
            return ('shop_type', 'username', 'keywords', 'title', 'itemid')
        return []

    def get_queryset(self, request):
        """
        根据请求的模型名称获取对应的查询集。
        """

        # model_name = request.GET.get('model', '')
        # if model_name == 'FollowPrice':
        #     return FollowPrice.objects.all()
        # return SkuKeywords.objects.all()
        qs = super().get_queryset(request)
        if hasattr(request.user, 'userprofile') and not request.user.userprofile.is_leader:
            return qs.filter(username=request.user.username)
        return qs

    def get_FollowPrice_data(self, request):
        """
        获取FollowPrice符合条件的数据列表，这里可添加具体的筛选条件。
        """
        keywords = request.GET.get('keywords')
        if keywords:
            queryset = FollowPrice.objects.filter(keywords__icontains=keywords.strip(),
                                    keywords__isnull=False)
        else:
            queryset = FollowPrice.objects.all()
        # queryset = FollowPrice.objects.all()
        
        # data = list(
        #     queryset.values('id', 'storename', 'shop_type', 'keywords',
        #                     'username', 'title', 'link', 'price',
        #                     'salesvolume', 'pic', 'price2', 'salesvolume2',
        #                     'pic2', 'itemid', 'lowvalue', 'username',
        #                     'opdate'))
        return queryset

    def get_SkuKeywords_data(self, request):
        """
        获取SkuKeywords符合条件的数据列表，同样可按需添加筛选条件。
        """
        queryset = SkuKeywords.objects.all()
        # 例如：queryset = queryset.filter(description__icontains='test')
        # data = list(
        #     queryset.values('sku', 'keywords', 'lowvalue', 'ebay', 'ali'))
        return queryset

    def get_urls(self):

        urls = super().get_urls()
        custom_urls = [
            path('insert_data/', self.admin_site.admin_view(self.insert_data)),
        ]
        return custom_urls + urls

    def insert_data(self, request):
        # if request.method == 'POST':
            # try:
            #     data = json.loads(request.body.decode('utf-8'))
            #     selected_model_b_ids = data.get('selected_model_b_ids', [])
            #     for model_b_id in selected_model_b_ids:
            #         model_b = ModelB.objects.get(pk=model_b_id)
            #         ModelA.objects.create(name=model_b.name,
            #                               description=model_b.description)
            #     return JsonResponse({
            #         'status': 'success',
            #         'message': '数据插入成功！'
            #     })
            # except:
            #     return JsonResponse({
            #         'status': 'error',
            #         'message': '数据插入出现错误，请检查！'
            #     })
        return JsonResponse({'status': 'error', 'message': '请求方法不正确！'})


# admin.site.register(Fpe, CombinedAdminView)
# admin.site.register(SkuKeywordsAnotherProxy, CombinedAdminView)

# 修改后的 FollowPriceAdmin，让 itemid 可以编辑并保存
class FollowPriceAdmin(admin.ModelAdmin):
    list_display = [
        'id', 'storename', 'shop_type', 'itemid', 'keywords', 'display_pic', 'username', 'title', 'link',
        'price', 'salesvolume', 'price2', 'salesvolume2', 'display_pic2', 'lowvalue', 'opdate', 'productid'
    ]
    list_editable = ('itemid',)
    list_display_links = ('id', 'storename')
    search_fields = ('id', 'shop_type', 'username', 'keywords','link', 'title', 'itemid', 'productid', 'opdate')
    list_filter = (FollowPriceStatusFilter,)

    def display_pic(self, obj):
        """Display the product pic in the admin list view with hover effect."""
        if obj.pic:
            return format_html(
                '<div style="position: relative; display: inline-block;">'
                '<img src="{}" style="max-height: 50px; transition: transform 0.2s; z-index: 1;" class="product-pic" />'
                '<style>'
                '.product-pic:hover {{ transform: scale(12); z-index: 10000; position: relative; }}'
                '</style>'
                '</div>',
                obj.pic
            )
        return "No pic"
    display_pic.short_description = "产品图片"

    def display_pic2(self, obj):
        if obj.pic2:
            return format_html(
                '<div style="position: relative; display: inline-block;">'
                '<img src="{}" style="max-height: 50px; transition: transform 0.2s; z-index: 1;" class="product-pic" />'
                '<style>'
                '.product-pic:hover {{ transform: scale(12); z-index: 10000; position: relative; }}'
                '</style>'
                '</div>',
                obj.pic2
            )
        return "-"
    display_pic2.short_description = '图片2'

    def get_paginator(self, request, queryset, per_page):
        from django.core.paginator import Paginator
        return Paginator(queryset, 20)
    
    def has_add_permission(self, request):
        return False

    def has_change_permission(self, request, obj=None):
        return True

    def has_delete_permission(self, request, obj=None):
        return False

    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        form.base_fields['itemid'].required = False
        return form

# 注册到 admin
admin.site.register(FollowPrice, FollowPriceAdmin)



class SkuKeyHistoryAdmin(admin.ModelAdmin):
    list_display = ['sku', 'chargeman', 'keywords',  'username','fromprice','toprice','ebay',
                    'ali','opdate']  # 在列表页面显示的字段
    search_fields = ('sku', 'keywords', 'chargeman')
    list_per_page = 20
    list_filter = ['keywords']
    save_as = True
    actions_on_top = True
    sort_by = ['keywords', 'sku']
    def has_add_permission(self, request):
        return False
    def has_delete_permission(self, request, obj = None):
        return False
    def has_change_permission(self, request, obj = None):
        return False
    def get_paginator(self, request, queryset, per_page):
        return Paginator(queryset, 20)
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        # Get keywords from URL parameters
        # keywords = request.GET.get('keywords')
        # if keywords:
        #     qs = qs.filter(keywords__icontains=keywords)
        if hasattr(request.user, 'userprofile') and not request.user.userprofile.is_leader:
            qs = qs.filter(username=request.user.username)
        return qs
    def save_model(self, request, obj, form, change):
        if not obj.username:
            obj.username = request.user.username
        obj.save()

# admin.site.register(SkuKeywords_history, SkuKeyHistoryAdmin)


class RatesAdmin(admin.ModelAdmin):
    list_display = ['currency_simplename','currency_name',                     'opdate']  # 在列表页面显示的字段

    search_fields = ('currency_simplename','currency_name', 'opdate')
    def has_add_permission(self, request):
        return False
    def has_delete_permission(self, request, obj = None):
        return False
    def has_change_permission(self, request, obj = None):
        return True
# admin.site.register(Rates, RatesAdmin)

class CrawlExceptAdmin(admin.ModelAdmin):
    list_display = ['shop_type', 'keywords', 'exceptcon','opdate']  # 在列表页面显示的字段

    search_fields = ('shop_type', 'keywords', 'exceptcon','opdate')
    def has_add_permission(self, request):
        return False
    def has_delete_permission(self, request, obj = None):
        return False
    def has_change_permission(self, request, obj = None):
        return False

# admin.site.register(CrawlExcept, CrawlExceptAdmin)

# @admin.register(SkuKeywords_history)
# class SkuKeywordsHistoryAdmin(admin.ModelAdmin):
#     list_display = ['historyid','sku', 'chargeman', 'keywords',  'username','fromprice','toprice','ebay',
#                     'ali','opdate']  # 在列表页面显示的字段
#     search_fields = ('sku', 'keywords', 'chargeman')
#     def get_object(self, request, object_id, from_field=None):
#         # Use the primary key or another unique field
#         return SkuKeywords_history.objects.get(pk=object_id)
#     def has_add_permission(self, request):
#         return False
#     def has_delete_permission(self, request, obj = None):
#         return False
#     def has_change_permission(self, request, obj = None):
#         return False
# admin.site.register(SkuKeywords_history, SkuKeywordsHistoryAdmin)

class CustomAdminSite(admin.AdminSite):
    class Media:
        css = {
            'all': (static('css/admin_custom.css'),)
        }

# admin_site = CustomAdminSite(name='custom_admin')

# # 然后使用 custom_admin_site 注册您的模型
# admin_site.register(FollowPrice, FollowPriceAdmin)
